#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(int argc, char *argv[])
{
    int sockfd;
    char buffer[1024];
    struct sockaddr_in server_addr; //定义服务器端套接口数据结构
    struct hostent *host;
    int nbytes, portnumber;
    if (argc != 3)
    {
        fprintf(stderr, "Usage:%s hostname portnumber\a\n", argv[0]);
        exit(1);
    }
    //获得命令行的第二个参数——主机名
    if ((host = gethostbyname(argv[1])) == NULL)
    {
        fprintf(stderr, "Gethostname error\n");
        exit(1);
    }
    if ((portnumber = atoi(argv[2])) < 0) //获得命令行的第三个参数——端口号，atoi()把字符串转换成整型数
    {
        fprintf(stderr, "Usage:%s hostname portnumber\a\n", argv[0]);
        exit(1);
    }
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        fprintf(stderr, "Socket Error:%s\n\a", strerror(errno));
        exit(1);
    }
    //客户程序填充服务端的资料
    bzero(&server_addr, sizeof(struct sockaddr_in)); //清空表示地址的结构体变量
    server_addr.sin_family = AF_INET;                //设置addr的成员变量
    server_addr.sin_port = htons(portnumber);
    server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr *)host->h_addr)));
    //客户程序发起连接请求
    if (connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
    {
        fprintf(stderr, "Connect Error:%s\a\n", strerror(errno));
        exit(1);
    }
    //连接成功，调用read读取服务器发送来的数据
    if ((nbytes = read(sockfd, buffer, 1024)) == -1)
    {
        fprintf(stderr, "Read Error:%s\n", strerror(errno));
        exit(1);
    }
    buffer[nbytes] = '\0';
    printf("I have received:%s\n", buffer); //输出接收到的数据
    close(sockfd);                          //结束通信
    exit(0);
}